/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.chatapp.Databaseacces;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;



/**
 *
 * @author bgorriz
 */
public class ImpXmlDbDataSource implements XmlDbDataSource {

    private static ImpXmlDbDataSource dataSourceInstance = null; 
    private final String URI;
    private final String driver;
    private final String username;
    private final String pass;
   
    
       
    private ImpXmlDbDataSource() {
        Properties prop = null;
        try {
            prop = PropertyReader.readPropertyFile("database.properties");
            
        } catch (IOException ex) {
            Logger.getLogger(ImpXmlDbDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }
       this.driver=prop.getProperty("XmlDbDataSource/driverClassName");
        this.URI=prop.getProperty("XmlDbDataSource/url");
        this.username=prop.getProperty("XmlDbDatasource/user");
        this.pass=prop.getProperty("XmlDbDatasource/password");
    
    }

    public static synchronized ImpXmlDbDataSource getinstanceDataSource(){
        
         if(dataSourceInstance==null)
        {
            dataSourceInstance= new ImpXmlDbDataSource();
        }
        return dataSourceInstance;
        
        
    }   
    
    
    
    
    
    public Collection getCollection() throws XMLDBException {
       
        initDataSource();
        return DatabaseManager.getCollection(URI);

       
    }

    public Collection getCollection(String aUserName, String aPassword) throws XMLDBException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    

    private void initDataSource()  {
        
        try {
            
            
            Class cl = Class.forName(driver);
           Database database = (Database) cl.newInstance();
            DatabaseManager.registerDatabase(database);
            
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ImpXmlDbDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex) {
            Logger.getLogger(ImpXmlDbDataSource.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(ImpXmlDbDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (XMLDBException ex) {
            Logger.getLogger(ImpXmlDbDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }
      
      
        
    }
}